package edu.sju.chenshu.system.service.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.sju.chenshu.common.core.constants.HttpConstants;
import edu.sju.chenshu.common.core.domain.LoginUser;
import edu.sju.chenshu.common.core.domain.Result;
import edu.sju.chenshu.common.core.domain.vo.LoginUserVO;
import edu.sju.chenshu.common.core.enums.ResultCode;
import edu.sju.chenshu.common.core.enums.UserIdentity;
import edu.sju.chenshu.common.core.service.BaseService;
import edu.sju.chenshu.common.security.service.TokenService;
import edu.sju.chenshu.system.domain.sysuser.SysUser;
import edu.sju.chenshu.system.domain.sysuser.dto.SysUserSaveDTO;
import edu.sju.chenshu.system.mapper.sysuser.SysUserMapper;
import edu.sju.chenshu.system.service.sysuser.ISysUserService;
import edu.sju.chenshu.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    //在不重启服务的前提下定期更换secret
    @Value("${jwt.secret}")
    private String secret;

    @Override
    public Result<String> login(String userAccount, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //select password from tb_sys_user where user_account = #{userAccount};
        SysUser sysUser = sysUserMapper.selectOne(
                queryWrapper
                        .select(SysUser::getUserId, SysUser::getPassword,  SysUser::getNickName)
                        .eq(SysUser::getUserAccount, userAccount)
        );
        if (sysUser == null) {
            return Result.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if (BCryptUtils.matchesPassword(password, sysUser.getPassword())) {
            return Result.ok(
                    tokenService.createToken(sysUser.getUserId(), secret, UserIdentity.ADMIN.getValue(), sysUser.getNickName(), null));
        }
        return Result.fail(ResultCode.FAILED_LOGIN);
    }

    @Override
    public Result<Void> logout(String token) {
        if (StrUtil.isNotEmpty(token) &&
                token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return toResult(tokenService.deleteLoginUser(token, secret));
    }

    @Override
    public Result<LoginUserVO> info(String token) {
        if (StrUtil.isNotEmpty(token) &&
                token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if (loginUser == null) {
            return Result.fail();
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return Result.ok(loginUserVO);
    }

    @Override
    public Result<Void> add(SysUserSaveDTO sysUserSaveDTO) {
        List<SysUser> sysUserList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));
        if (CollectionUtil.isNotEmpty(sysUserList)) {
            //用户已存在
            return Result.fail(ResultCode.AILED_USER_EXISTS);
        }
        //将DTO转为实体
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
        return toResult(sysUserMapper.insert(sysUser));
    }
}
